import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:foxue/global.dart';
import 'package:flutter/material.dart';
import 'package:foxue/http/api.dart';
import 'package:foxue/page/detail.dart';

class SearchPage extends StatefulWidget {
  SearchPage({Key key}) : super(key: key);
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  TextEditingController _searchController = new TextEditingController();
  var _key = '';
  var _items = [];
  @override
  void initState() {
    super.initState();
  }

  search(key) {
    if (key != null && key.trim() != '') {
      EasyLoading.show(status: '搜索中...');
      searchFoxue(key).then((res) {
        EasyLoading.dismiss();
        if (res == null || res['result'].length == 0) {
          EasyLoading.showToast('匹配失败');
        } else {
          setState(() {
            _key = res['key'];
            _items = res['result'];
          });
        }
      });
    } else {
      EasyLoading.showToast('匹配失败');
    }
  }

  List<Widget> renderDirectory(items) {
    List<Widget> list = [];
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      list.add(
        InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DetailPage(
                  id: item['id'].toString(),
                ),
              ),
            );
          },
          child: Container(
            width: MediaQuery.of(context).size.width,
            margin: EdgeInsets.all(5),
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 1,
                  color: Global.primaryColor.withOpacity(0.1),
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(width: 5),
                Text(
                  '${(i + 1).toString()}：',
                  style: TextStyle(
                    fontFamily: 'fangzhengkai',
                    color: Global.primaryColor,
                    fontWeight: FontWeight.w700,
                    fontSize: 17,
                  ),
                ),
                SizedBox(width: 10),
                Expanded(
                  child: Text(
                    item['name'],
                    style: TextStyle(
                      fontFamily: 'fangzhengkai',
                      color: Global.fontColor,
                      fontSize: 17,
                      fontWeight: FontWeight.w700,
                      decoration: TextDecoration.underline,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FlutterEasyLoading(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            color: Global.backgroundColor,
          ),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(0, Global.paddingTop, 0, 10),
                decoration: BoxDecoration(
                  color: Global.backgroundColor,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      offset: Offset(0, 2),
                      blurRadius: 2,
                      spreadRadius: 2,
                    )
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(width: 5),
                    IconButton(
                      icon: Icon(
                        Icons.chevron_left,
                        color: Global.primaryColor,
                        size: 27,
                      ),
                      tooltip: '返回首页',
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    Expanded(
                      child: TextField(
                        controller: _searchController,
                        keyboardType: TextInputType.text,
                        decoration: InputDecoration.collapsed(
                          hintText: "输入您要搜索的关键词",
                          hintStyle: TextStyle(
                            fontFamily: 'fangzhengkai',
                            fontWeight: FontWeight.bold,
                            color: Global.fontColor,
                            fontSize: 17,
                          ),
                        ),
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'fangzhengkai',
                          color: Global.fontColor,
                        ),
                        cursorColor: Global.fontColor,
                        onSubmitted: (text) {
                          search(text);
                        },
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        search(_searchController.text.toString());
                      },
                      child: Container(
                        width: 40,
                        child: Icon(
                          Icons.search,
                          color: Global.primaryColor,
                          size: 27,
                        ),
                      ),
                    ),
                    SizedBox(width: 10),
                  ],
                ),
              ),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        children: renderDirectory(_items),
                      ),
                      SizedBox(height: 35),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
